/**
 * @ 教务系统TOKEN管理
 */

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const USER = 'edu-cloud-users'
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let action = event.action;
  /** 获取OPENID */
  let openid = event.openid || wxContext.OPENID;
  /** 获取用户基础信息 */
  let userBase = {};
  let queryRes = await db.collection(USER).where({
    openid
  }).get();
  if (queryRes.data.length == 0) {
    return {
      errCode: -1,
      errMsg: '该用户未绑定学号信息'
    }
  } else {
    userBase = queryRes.data[0];
  }
  switch (action) {
    /** 刷新用户对应TOKEN */
    case 'flushToken': {
      let authRes = await cloud.callFunction({
        name: 'edu-cloud-api',
        data: {
          action: 'authUser',
          resHandle:true,
          xh: userBase.bindId,
          password: userBase.bindPwd
        }
      })
      /** 根据结果刷新TOKEN */
      if(authRes.result.errCode == -1){
        return authRes.result;
      }else{
        await db.collection(USER).where({
          openid
        }).update({
          data:{
            token:authRes.result.data.token
          }
        })
        return authRes.result;
      }
      break
    }
  }
}